In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.
The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.
In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!
We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
Make sure that you've downloaded the required human and dog datasets:
Note: if you are using the Udacity workspace, you DO NOT need to re-download these - they can be found in the /data folder as noted in the cell below.
Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dog_images.
Download the human dataset. Unzip the folder and place it in the home directory, at location /lfw.
Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.
In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.
import numpy as np
from glob import glob
# load files from human and dogs
human_files = np.array(glob('/data/lfw/*/*'))
dog_files = np.array(glob('/data/dog_images/*/*/*'))
#print number of images in each dataset
print('There are {} total human images.'.format(len(human_files)))
print('There are {} total dog images.'.format(len(dog_files)))
# import liberaries
import torch
import torchvision.models as models
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets
from PIL import ImageFile
from PIL import Image
import PIL
ImageFile.LOAD_TRUNCATED_IMAGES = True
use_cuda = torch.cuda.is_available()
if use_cuda:
print('cuda is avaliable ... ' )
print('PyToch Version : ',torch.__version__)
In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.
OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
The following code example will use pretrained Haar cascade models to detect faces in an image. First, a
CascadeClassifieris created and the necessary XML file is loaded using theCascadeClassifier::load method. Afterwards, the detection is done using theCascadeClassifier,detectMultiScalemethod, which returns boundary rectangles for the detected faces.
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline
# 1. extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# 2. load image (rgb)
img_rgb = cv2.imread(human_files[125])
#3. convert image to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
#4. find faces in image
faces = face_cascade.detectMultiScale(img_gray)
#5. print num of faces detected in image
print('Numbrer of faces detected = {}'.format(len(faces)))
#6. get bounding box for each detected face
for x, y, w, h in faces:
# add bounded box to the colored image
# cv2.rectangle(image, start_point, end_point, color, thickness)
cv2.rectangle(img_rgb, (x, y), (x+w, y+h), (255,0,0) , 2)
#7. Convert RGB image to RGB image for plotting
face_rgb = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2RGB)
#8. display the image, along with bounding box
plt.imshow(face_rgb)
plt.show()
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.
In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.
We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
#from mtcnn import MTCNN
def face_detector(img_path):
img_rgb = cv2.imread(img_path)
img_gray= cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
faces = face_cascade.detectMultiScale(img_gray)
return len(faces) > 0
Question 1: Use the code cell below to test the performance of the face_detector function.
human_files have a detected human face? dog_files have a detected human face? Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.
Answer: The face detector isn't perfect as it detect face in 16% of dog images. and it fails to detect 4% of human images.
from tqdm import tqdm_notebook as tqdm
def face_detector_performance(files_short , file_name):
counter = []
incorrect_imgs = []
[(incorrect_imgs.append(file)) if ((face_detector(file))^bool(file_name =='human')) else (counter.append(1))for file in tqdm(files_short) ]
return sum(counter), incorrect_imgs
total = 100
human_files_short = human_files[:total]
dog_files_short = dog_files[:total]
n_faces_in_human_files, error_list_human_files = face_detector_performance(human_files_short, 'human')
n_faces_in_dog_files , error_list_dog_files = face_detector_performance(dog_files_short, 'dog')
print('Number of faces detected in human files short is {}/{} \t\t cost = {}%'.format(n_faces_in_human_files, total,
100-n_faces_in_human_files))
print('Number of faces detected in dog files short is {}/{} \t\t cost = {}%'.format(100-n_faces_in_dog_files, total,
100-n_faces_in_dog_files))
error_list_human_files
#error_list_dog_files
# Display images
def show_erroneous (my_list, row, col, size):
plt.figure(figsize=(20,20))
for i, img in enumerate(my_list):
image = PIL.Image.open(img)
plt.subplot(row,col,i+1)
plt.title(img.split('/')[-1].split('.')[0] , size = size)
plt.axis('off')
plt.imshow(image);
print
# print detector errors form human files
show_erroneous(error_list_human_files, 2,2,20)
# print detector errors form dog files
show_erroneous(error_list_dog_files, 4,4,15)
We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
doesn't work
!pip install mtcnn
import mtcnn
# print version
print(mtcnn.__version__)
from mtcnn import MTCNN
from matplotlib.patches import Rectangle
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# cextract pre-trained face detector
MTCNN_detector = MTCNN()
# load image (rgb)
img_rgb = cv2.imread(human_files[20])
#convert image to grayscale
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_RGB2GRAY)
#detect the face
faces = MTCNN_detector.detect_faces(img_gray)
#print num of faces detected in image
print('Numbrer of faces detected = {}'.format(len(faces)))
# get bounding box for each detected face
for x, y, w, h in faces:
# add bounded box to the colored image
# cv2.rectangle(image, start_point, end_point, color, thickness)
cv2.rectangle(img_rgb, (x, y), (x+w, y+h), (255,0,0) , 2)
#Convert RGB image to RGB image for plotting
face_rgb = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2RGB)
#8. display the image, along with bounding box
plt.imshow(face_rgb)
plt.show()
In this section, we use a pre-trained model to detect dogs in images.
The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.
VGG16_model = models.vgg16(pretrained=True)
if use_cuda:
VGG16_model = VGG16_model.cuda()
else:
print('cuda NOT avaliable...')
print(VGG16_model)
Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.
In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.
Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.
from torch.autograd import Variable
def predict_breed(img_path,model):
'''
Use pre-trained VGG-16 model to obtain index corresponding to
predicted ImageNet class for image at specified path
Args:
img_path: path to an image
Returns:
Index corresponding to VGG-16 model's prediction
'''
# 1. Load image from its path
image = Image.open(img_path)
# 2. pre-process an image from the given img_path (convert image to tensor)
data_transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406),
(0.229, 0.224, 0.225))
])
tensor_img = data_transform(image).float()
tensor_img = tensor_img.unsqueeze(0)
tensor_img = Variable(tensor_img)
# 3. Move to cuda
if use_cuda:
tensor_img = tensor_img.cuda()
#4. make prediction and move it to cuda
output = model(tensor_img)
#5. Move to cpu
if use_cuda:
output = output.cpu()
#5. Return the *index* of the predicted class for that image
torch.no_grad()
index = output.data.numpy().argmax()
return index
While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).
Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path, model):
index= predict_breed(img_path, model)
return (151 <= index and index <= 268)
Question 2: Use the code cell below to test the performance of your dog_detector function.
human_files_short have a detected dog? dog_files_short have a detected dog?Answer:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.
from tqdm import tqdm_notebook as tqdm
def dog_detector_performance(files_short , file_name, model):
counter = []
incorrect_imgs = []
[(incorrect_imgs.append(file)) if (bool(dog_detector(file, model))^bool(file_name =='dog')) else (counter.append(1))for file in tqdm(files_short) ]
return sum(counter), incorrect_imgs
total = 100
human_files_short = human_files[:total]
dog_files_short = dog_files[:total]
n_faces_in_human_files, error_list_human_files = dog_detector_performance(human_files_short, 'human',VGG16_model)
n_dogs_in_dog_files , error_list_dog_files = dog_detector_performance(dog_files_short, 'dog',VGG16_model)
n_dogs_in_human_files = total - n_faces_in_human_files
print('Number of dogs detected in human files short is {}/{} images \t\t cost = {}%'.format(n_dogs_in_human_files, total,
n_dogs_in_human_files))
print('Number of dogs detected in dog files short is {}/{} images \t\t cost = {}%'.format(n_dogs_in_dog_files, total,
100-n_dogs_in_dog_files))
# print detector errors form human files
show_erroneous(error_list_human_files, 2,2 ,25);
# print detector errors form dog files
show_erroneous(error_list_dog_files, 2,5,15);
We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.
import torchvision.models as models
squeezenet11_model = models.squeezenet1_1(pretrained = True)
if use_cuda:
squeezenet11_model = squeezenet11_model.cuda()
else:
print('cuda NOT avaliable...')
print(squeezenet11_model)
total = 100
human_files_short = human_files[:total]
dog_files_short = dog_files[:total]
n_faces_in_human_files, error_list_human_files = dog_detector_performance(human_files_short, 'human',squeezenet11_model)
n_dogs_in_dog_files , error_list_dog_files = dog_detector_performance(dog_files_short, 'dog',squeezenet11_model)
n_dogs_in_human_files = total - n_faces_in_human_files
print('Number of dogs detected in human files short is {}/{} \t\t cost = {}%'.format(n_dogs_in_human_files, total,
n_dogs_in_human_files))
print('Number of dogs detected in dogs files short is {}/{} \t\t cost = {}%'.format(n_dogs_in_dog_files, total,
100-n_dogs_in_dog_files))
show_erroneous(error_list_human_files, 2, 2,15)
show_erroneous(error_list_dog_files, 2, 3,15)
Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.
| Brittany | Welsh Springer Spaniel |
|---|---|
![]() |
![]() |
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
| Curly-Coated Retriever | American Water Spaniel |
|---|---|
![]() |
![]() |
Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.
Yellow Labrador | Chocolate Labrador | Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dog_images/train, dog_images/valid, and dog_images/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!
from torch.utils.data.sampler import SubsetRandomSampler
from torch.autograd import Variable
import random
import os
## Specify appropriate transforms
# https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomRotation(20),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'valid': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'test': transforms.Compose([
transforms.CenterCrop(256),
transforms.Resize(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
print("Initializing Datasets and Dataloaders...")
data_dir = '/data/dog_images/'
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'valid', 'test']}
loaders_data = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size = 20,
shuffle = True, num_workers = 0)
for x in ['train', 'valid', 'test']}
loaders_data
image_datasets
# Some statistics
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'valid', 'test']}
classes_name = image_datasets['train'].classes
n_classes = len(classes_name)
print('Number of train images = ' ,dataset_sizes['train'] )
print('Number of validation images = ',dataset_sizes['valid'] )
print('Number of test data images = ' ,dataset_sizes['test'] )
print('Number of classes = ' ,n_classes )
def imshow(img):
img = img.transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
img = std * img + mean
img = np.clip(img, 0, 1)
plt.imshow(img)
##############################################################3
def show_shample_of_images (loaders_data, row, n_images, fig_size = (25, 5)):
images, classes = next(iter(loaders_data))
images = images.numpy()
fig = plt.figure(figsize=fig_size)
for i in np.arange(n_images):
ax = fig.add_subplot(row, n_images/row, i+1, xticks=[], yticks=[])
imshow(images[i])
class_names = image_datasets['train'].classes
ax.set_title(class_names[classes[i]].split(".")[1])
show_shample_of_images(loaders_data['train'], 2, 20, fig_size = (24, 4))
show_shample_of_images(loaders_data['valid'], 2, 20, fig_size = (24, 4))
show_shample_of_images(loaders_data['test'], 2, 20, fig_size = (30, 5))
Question 3: Describe your chosen procedure for preprocessing the data.
Answer:
Test and Validation datasets:
Train dataset :
Create a CNN to classify dog breed. Use the template in the code cell below.
!pip install torchsummary
conv_channels = {
'layer0' :3,
'layer1' :16,
'layer2' :32,
'layer3' :64,
'layer4' :128,
'layer5' :256,
}
hparameters={
'n_batches' : 128,
'n_epochs' : 10,
'n_fc_nodes' : 512,
'learning_rate' :0.01 ,
'momentum' : 0.9,
}
hparameters['n_classes'] = n_classes
hparameters
# define the CNN architecture
class Net(nn.Module):
### TODO: choose an architecture, and complete the class
def __init__(self):
super(Net, self).__init__()
## Define Convolution layers
self.conv1 = nn.Conv2d (conv_channels['layer0'], conv_channels['layer1'], kernel_size = 3, padding = 1 , stride = 1)
self.conv2 = nn.Conv2d (conv_channels['layer1'], conv_channels['layer2'], kernel_size = 3, padding = 1 , stride = 1)
self.conv3 = nn.Conv2d (conv_channels['layer2'], conv_channels['layer3'], kernel_size = 3, padding = 1 , stride = 1)
self.conv4 = nn.Conv2d (conv_channels['layer3'], conv_channels['layer4'], kernel_size = 3, padding = 1 , stride = 1)
self.conv5 = nn.Conv2d (conv_channels['layer4'], conv_channels['layer5'], kernel_size = 3, padding = 1 , stride = 1)
self.pool = nn.MaxPool2d(2,2)
self.dropout = nn.Dropout(0.3)
# Define BatchNormalization
self.bn_1 = nn.BatchNorm2d(conv_channels['layer1'])
self.bn_2 = nn.BatchNorm2d(conv_channels['layer2'])
self.bn_3 = nn.BatchNorm2d(conv_channels['layer3'])
self.bn_4 = nn.BatchNorm2d(conv_channels['layer4'])
self.bn_5 = nn.BatchNorm2d(conv_channels['layer5'])
## Define fully connected layers
self.fc1 = nn.Linear(conv_channels['layer5']*7*7, hparameters['n_fc_nodes'])
self.fc2 = nn.Linear(hparameters['n_fc_nodes'] , hparameters['n_fc_nodes'])
self.output = nn.Linear( hparameters['n_fc_nodes'], hparameters['n_classes'])
def forward(self, x):
####################### Define forward behavior ######################################
#CONV_1
x = F.relu(self.conv1(x)) #=> img = (224, 224) n_channels : 3 ==> 16
x = self.bn_1(self.pool(x)) #=> img = (112, 112) n_channels = 16
#CONV_2
x = F.relu(self.conv2(x)) #=> img = (112, 112) n_channels : 16 ==> 32
x = self.bn_2(self.pool(x)) #=> img = (56, 56) n_channels = 32
#CONV_3
x = F.relu(self.conv3(x)) #=> img = (56, 56) n_channels : 32 ==> 64
x = self.bn_3(self.pool(x)) #=> img = (28, 28) n_channels = 64
#CONV_4
x = F.relu(self.conv4(x)) #=> img = (28, 28) n_channels : 64 ==> 128
x = self.bn_4(self.pool(x)) #=> img = (14, 14) n_channels = 128
#CONV_5
x = F.relu(self.conv5(x)) #=> img = (14, 14) n_channels : 128 ==> 256
x = self.bn_5(self.pool(x)) #=> img = (7, 7) n_channels = 256
####################### FLATTEN ####################################################
x = x.view(x.size(0), conv_channels['layer5']*7*7) # n_channels * weidth * height
#####################################################################################
#FULLY-CONNECTED_1 (HIDDEN)
x = F.relu(self.fc1(x))
x = self.dropout(x)
#FULLY-CONNECTED_2 (HIDDEN)
x = F.relu(self.fc2(x))
x = self.dropout(x)
#FULLY-CONNECTED_3 (OUTPUT)
x = self.output(x)
return x
#####################################################################################
# Create new model
model_scratch = Net()
# move tensors to GPU if CUDA is available
if use_cuda:
model_scratch.cuda()
from torchsummary import summary
summary(model_scratch, (3, 224, 224))
Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.
Answer:
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.
### select loss function
criterion_scratch = nn.CrossEntropyLoss()
### select optimizer
optimizer_scratch = optim.SGD(model_scratch.parameters() , lr = hparameters['learning_rate'], momentum=hparameters['momentum'])
# scheduler = optim.lr_scheduler.StepLR(optimizer_scratch, step_size=100, gamma=0.9)
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.
import time
import numpy as np
def train(num_epochs,model, dataloaders, criterion, optimizer, use_cuda, save_path):
val_acc_history=[]
val_loss_history=[]
train_acc_history=[]
train_loss_history=[]
valid_loss_min = np.Inf
best_loss = np.Inf
no_improve = 0
early_stop = False
since = time.time()
for epoch in range(1, num_epochs + 1):
start_epoch = time.time()
print('Epoch {}/{}'.format(epoch, num_epochs))
# Each epoch has a training and validation phase
for phase in ['train', 'valid']:
if phase == 'train':
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for batch_idx, (inputs, labels) in enumerate(dataloaders[phase]):
if use_cuda:
inputs, labels = inputs.cuda(), labels.cuda()
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
# Get model outputs and calculate loss
# Special case for inception because in training it has an auxiliary output. In train
# mode we calculate the loss by summing the final output and the auxiliary output
# but in testing we only consider the final output.
outputs = model(inputs)
loss = criterion(outputs, labels)
_, preds = torch.max(outputs, 1)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
if batch_idx % 4 == 0 :
print('-',end='')
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / len(dataloaders[phase].dataset)
epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)
print('\n{} epoch \t Loss: {:.6f} \t Accuracy: {:.6f}'.format(phase, epoch_loss, epoch_acc))
# deep copy the model
if phase == 'valid' and epoch_loss < best_loss:
print('-'*84)
print('\nValidation loss decreased ({:.6f} ----> {:.6f}) Saving model...'.format(best_loss, epoch_loss))
best_loss = epoch_loss
torch.save(model.state_dict(), save_path)
no_improve = 0
elif phase == 'valid' and epoch_loss > best_loss:
no_improve += 1
if phase == 'valid':
val_acc_history.append(epoch_acc)
val_loss_history.append(epoch_loss)
else:
train_acc_history.append(epoch_acc)
train_loss_history.append(epoch_loss)
if epoch > 2 and no_improve == 3:
print('Early stopping!' )
early_stop = True
else:
early_stop = False
# Check early stopping condition
if early_stop:
print("Stopped")
break
epoch_time = time.time() - start_epoch
print('Epoch takes {:.0f} min {:.0f} sec'.format(epoch_time // 60,epoch_time % 60))
print('='*84)
time_elapsed = time.time() - since
print('Training complete in {:.0f} min {:.0f} sec'.format(time_elapsed // 60, time_elapsed % 60))
print('Best validation Loss: {:6f}'.format(best_loss))
# load best model weights
model.load_state_dict(torch.load(save_path))
history = {'train_acc' :train_acc_history,
'train_loss':train_loss_history,
'val_acc' :val_acc_history,
'val_loss' :val_loss_history,}
return history , model
# train the model
loaders_scratch = loaders_data
history, model_scratch = train(hparameters['n_epochs'],model_scratch,
loaders_scratch, criterion_scratch,
optimizer_scratch, use_cuda, 'model_scratch.pt')
## load the model that got the best validation accuracy
model_scratch.load_state_dict(torch.load('model_scratch.pt'))
from torchvision.utils import make_grid
kernels = model_scratch.conv1.weight.detach().clone()
kernels = kernels - kernels.min()
kernels = kernels / kernels.max()
img = make_grid(kernels)
plt.imshow(img.permute(1, 2, 0))
doesn't work
!pip install --upgrade torch
!pip install tensorboard --upgrade
!python -m pip install grpcio-tools
!pip install tensorboard_logger
# from torch.utils.tensorboard import SummaryWriter
# # Writer will output to ./runs/ directory by default
# writer = SummaryWriter('./runs/model_scratch_experiment_1')
import os
root_logdir = os.path.join(os.curdir, 'my_logs')
import time
def get_run_logdir():
run_id = time.strftime('run_%Y_%m_%d-%H_%M_%S')
return os.path.join(root_logdir, run_id)
run_logdir = get_run_logdir()
print(run_logdir)
# !pip uninstall tensorboard-plugin-wit 1.8.0
# y
# !pip install -U transformers torch torchvision tensorboardX tf-nightly grpcio==1.24.3
%reload_ext tensorboard
%tensorboard --logdir=./my_logs --port=6006
history
train_acc = []
valid_acc = []
train_acc = [acc.cpu().numpy() for acc in history['train_acc']]
valid_acc = [acc.cpu().numpy() for acc in history['val_acc']]
plt.title("Training Accuacy VS Validation Accuracy.")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.plot(range(1,hparameters['n_epochs']+1),train_acc,label="Training Accuacy")
plt.plot(range(1,hparameters['n_epochs']+1),valid_acc,label="Validation Accuracy")
plt.xticks(np.arange(1, hparameters['n_epochs']+1, 1.0))
plt.legend()
plt.show()
plt.savefig('Training Accuacy VS Validation Accuracy - model scratch.png')
print('Image saved!')
import numpy as np
plt.title("Training Loss VS Validation Loss.")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.plot(range(1,hparameters['n_epochs']+1),history['train_loss'],label="Training Loss")
plt.plot(range(1,hparameters['n_epochs']+1),history['val_loss'],label="Validation Loss")
plt.xticks(np.arange(1, hparameters['n_epochs']+1, 1.0))
plt.legend()
plt.show()
plt.savefig('Training Loss VS Validation Loss - model scratch.png')
print('Image saved!')
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.
def test(loaders, model, criterion, use_cuda):
# monitor test loss and accuracy
test_loss = 0.
correct = 0.
total = 0.
model.eval()
for batch_idx, (data, target) in enumerate(loaders['test']):
# move to GPU
if use_cuda:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the model
output = model(data)
# calculate the loss
loss = criterion(output, target)
# update average test loss
test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
# convert output probabilities to predicted class
pred = output.data.max(1, keepdim=True)[1]
# compare predictions to true label
correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
total += data.size(0)
print('-',end='')
print('\nTest Loss: {:.6f}\n'.format(test_loss))
print('\nTest Accuracy: %2d%% (%2d/%2d)' % (
100. * correct / total, correct, total))
# call test function
test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.
Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).
If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.
## TODO: Specify data loaders
loaders_transfer = loaders_data
loaders_transfer
Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.
## TODO: Specify model architecture
model_transfer = models.densenet161(pretrained=True)
for param in model_transfer.parameters():
param.requires_grad = False
n_features = model_transfer.classifier.in_features
model_transfer.classifier = nn.Linear(n_features, hparameters['n_classes'])
if use_cuda:
model_transfer = model_transfer.cuda()
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer:
Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.
criterion_transfer = nn.CrossEntropyLoss()
optimizer_transfer = torch.optim.SGD(model_transfer.classifier.parameters(),
lr=hparameters['learning_rate'],
momentum = hparameters['momentum'])
Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.
# train the model
model_transfer, transfer_history =train(
3,
model_transfer,loaders_transfer,
criterion_transfer,optimizer_transfer, use_cuda, 'model_transfer.pt')
# load the model that got the best validation accuracy (uncomment the line below)
model_transfer.load_state_dict(torch.load('model_transfer.pt'))
transfer_history
doesn't work
train_acc = []
valid_acc = []
train_acc = [acc.cpu().numpy() for acc in transfer_history['train_acc']]
valid_acc = [acc.cpu().numpy() for acc in transfer_history['val_acc']]
plt.title("Training Accuacy VS Validation Accuracy.")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.plot(range(1,hparameters['n_epochs']+1),train_acc,label="Training Accuacy")
plt.plot(range(1,hparameters['n_epochs']+1),valid_acc,label="Validation Accuracy")
plt.ylim((0,0.4))
plt.xticks(np.arange(1, hparameters['n_epochs']+1, 1.0))
plt.legend()
plt.show()
plt.savefig('Training Accuacy VS Validation Accuracy - pretrained scratch.png')
print('Image saved!')
import numpy as np
plt.title("Training Loss VS Validation Loss.")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.plot(range(1,hparameters['n_epochs']+1),transfer_history['train_loss'],label="Training Loss")
plt.plot(range(1,hparameters['n_epochs']+1),transfer_history['val_loss'],label="Validation Loss")
plt.xticks(np.arange(1, hparameters['n_epochs']+1, 1.0))
plt.legend()
plt.show()
plt.savefig('Training Loss VS Validation Loss - pretrained scratch.png')
print('Image saved!')
doesn't work
scratch_val_Acc = []
pretrained_val_Acc = []
scratch_val_Acc = [acc.cpu().numpy() for acc in history['val_acc']]
pretrained_val_Acc = [acc.cpu().numpy() for acc in transfer_history['val_acc']]
plt.title("Scratch Model vs. Pretrained Model")
plt.xlabel("Training Epochs")
plt.ylabel("Validation Accuracy")
plt.plot(range(1,num_epochs+1),scratch_val_Acc,label="Pretrained-val-Acc")
plt.plot(range(1,num_epochs+1),pretrained_val_Acc,label="Scratch-Acc")
plt.ylim((0,0.5))
plt.xticks(np.arange(1, num_epochs+1, 1.0))
plt.legend()
plt.show()
plt.savefig('Scratch Model vs. Pretrained Model.png')
print('Image saved!')
Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.
test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
from extractor import Extractor
extractor = Extractor(list(model_transfer.children()))
extractor.activate()
extractor.info()
# Visualising the filters
import cv2
import torchvision.transforms as transforms
# plt.figure(figsize=(6, 6))
plt.figure(figsize=(25, 25))
for index, filter in enumerate(extractor.CNN_weights[0]):
if index == 64:
break
plt.subplot(8, 8, index + 1)
plt.imshow(filter[0, :, :].detach(), cmap='gray')
plt.axis('off')
plt.show()
img = cv2.cvtColor(cv2.imread('./images/Curly-coated_retriever_03896.jpg'), cv2.COLOR_BGR2GRAY)
plt.imshow(img, cmap='gray')
plt.show()
img_transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((128, 128)),
transforms.ToTensor(),
transforms.Normalize(0.5, 0.5)])
img = img_transform(img).float().unsqueeze(0)
featuremaps = [extractor.CNN_layers[0](img)]
for x in range(1, len(extractor.CNN_layers)):
featuremaps.append(extractor.CNN_layers[x](featuremaps[-1]))
# # Visualising the featuremaps
for x in range(len(featuremaps)):
plt.figure(figsize=(30, 30))
layers = featuremaps[x][0, :, :, :].detach()
for i, filter in enumerate(layers):
if i == 64:
break
plt.subplot(8, 8, i + 1)
plt.imshow(filter, cmap='gray')
plt.axis('off')
plt.savefig('featuremap/featuremap%s.png'%(x))
plt.show()
Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.
loaders_transfer = loaders_data
class_names = [item[4:].replace("_", " ") for item in loaders_transfer['train'].dataset.classes]
def predict_breed_transfer(img_path , model):
img = Image.open(img_path)
trans = transforms.Compose([transforms.Resize(256),
transforms.CenterCrop(244),
transforms.ToTensor(),
transforms.Normalize((0.5,0.5,.5),(0.5,0.5,0.5))])
img = trans(img)[:3,:,:].unsqueeze(0)
if use_cuda:
model = model.cuda()
img = img.cuda()
model.eval()
class_ = model(img)
output = class_names[torch.argmax(class_)]
return output
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and human_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.
Some sample output for our algorithm is provided below, but feel free to design your own user experience!

def run_app(img_path):
# Detect if the photo id dog or not
if dog_detector(img_path) :
#Say Hallo for the dog ^^
print("Hello, Dog")
#Predict the Dog breed
Class = predict_breed_transfer(img_path , model_transfer)
#Print the image
img = mpimg.imread(img_path)
imgplot = plt.imshow(img)
plt.axis('off')
plt.show()
print("The breed of the dog is :", Class)
print("="*50)
elif face_detector(img_path) :
#Say Hello for the human^^
print("Hello, Human")
#Predict the human resamplig of the dog breed
Class = predict_breed_transfer(img_path , model_transfer)
#Print the image
img = mpimg.imread(img_path)
imgplot = plt.imshow(img)
plt.axis('off')
plt.show()
print("The dog breed of the human is :", Class)
print("="*50)
else :
print("The image is neither dog nor human there is an error ")
img = mpimg.imread(img_path)
imgplot = plt.imshow(img)
plt.axis('off')
plt.show()
print("="*50)
In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?
Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer: (Three possible points for improvement)
# Create list of test image paths
for file in np.hstack((human_files[50:52], dog_files[50:52])):
run_app(file)
run_app('easy how to draw.jpeg')
run_app('heba.jpg')
run_app('heba2.jpg')
run_app('drawing1.jpg')
run_app('drawing2.png')
If you have any question about the starter code or your own implementation, please add it in the cell below.
For example, if you want to know why a piece of code is written the way it is, or its function, or alternative ways of implementing the same functionality, or if you want to get feedback on a specific part of your code or get feedback on things you tried but did not work.
Please keep your questions succinct and clear to help the reviewer answer them satisfactorily.
WHY my validation losses in model_scratch less than train loss?
On transfer_model WHY the history print the Net architecture?
I tried to visualize my result on tensorboard but all the trails failed.
Also tried to visualize feature map but failed.